package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信授权登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1:调用微信的服务端接口 把code appid app秘钥 还有一个固定属性grant_type
        String openid = getOpenId(userLoginDTO.getCode());

        //为了程序更优秀 做个校验
        if(openid==null){//说明授权失败--登录失败
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断 当前用户是否为新用户
        User user = userMapper.getByOpenId(openid);//通过openId查询用户
        //是null就 新增
        if(user==null){
            //说明 新用户 就重新new
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);//user要不要实现主键回显  有经验！！！
        }

        return user;
    }


    public String getOpenId(String code){

        // 创建HttpClient对象 创建HttpGet对象 HttpClient 发请求(设置参数)
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        /*
           {
                "session_key": "u1Gj3laoO/KRL8nFIz255Q==",
                "openid": "o1ybQ6rjMYEJa508hN_JzdZNjk08"
            }

            {
                "errcode": 40029,
                "errmsg": "invalid code, rid: 649d45d2-68cae49f-4da03a27"
            }
         */
        // 将json穿 变成对象
        JSONObject jsonObject = JSON.parseObject(json);
        // jsonObject表达一个json的对象  底层跟咱们map很像
        String openid = jsonObject.getString("openid");
        // map.put()  map.get(不存在的键)返回null

        return openid;
    }
}
